#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>

#include <sys/types.h>
#include <sys/stat.h>

#define BUFSIZE 512
#define MBRSIZE 446

int printmbr (int fd) {
  int i = 0;
  int nli = 0;
  unsigned char buf[BUFSIZE] = "";
  ssize_t len = 0;

  if ((len = read(fd, buf, BUFSIZE)) < BUFSIZE) {
    fprintf(stderr, "ERROR: read size=%lld\n", (long long) len);
    return -1;
  }

  printf("[000] ");
  for (i = 0, nli = i; i < BUFSIZE; i++, nli++) {
    if (((nli % 0x10 == 0) && (nli != 0)) || (MBRSIZE == nli)) {
      printf("\n");
      printf("[%03X] ", i);
      if (MBRSIZE == nli) {
	nli = 0;
      }
    }
    if (buf[i] < 0xF) {
      printf("0%X ", buf[i]);
    } else {
      printf("%X ", buf[i]);
    }
  }
  printf("\n");
  return len;
}

int clear_mbr (int fd) {
  char buf[MBRSIZE] = "";
  ssize_t len = 0;
  size_t ptr = 0;

  memcpy(buf, "0", MBRSIZE);
  while (ptr < MBRSIZE) {
    len = write(fd, buf, MBRSIZE - ptr);
    if (len < 0) {
      return errno;
    }
    ptr += len;
  }
  return 0;
}

int main (int argc, char **argv)
{
  int fd = -1;
  int wflag = 0;
  int oflag = O_RDONLY;
  int err = 0;

  if (argc >= 2) {
    if (strncmp("-w", argv[1], 2)) {
      fprintf(stderr, "Using %s [-w]\n", argv[0]);
      return 1;
    } else {
      wflag = 1;
      oflag = O_WRONLY;
    }
  }

  fd = open("/dev/sdc", oflag);
  if (fd < 0) {
    perror("open(/dev/sdc)");
    goto e_open;
  }

  if (wflag) { // write
    if ((err = clear_mbr(fd))) {
      fprintf(stderr, "ERROR: clear_mbr: %s\n", strerror(err));
      goto e_write;
    }
  } else { // read
    if (printmbr(fd) < 0) {
      goto e_read;
    }
  }

 e_write:
 e_read:
  close(fd);
 e_open:
  return 0;
}
